package com.ts.common.config;

import com.alibaba.fastjson.JSON;
import com.ts.animal.constant.AnimalConstant;
import com.ts.common.enums.ResultCode;
import com.ts.common.utils.ResponseResult;
import com.ts.common.utils.UtilSignature;
import com.ts.system.util.SystemUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class OpenApiInterceptor implements HandlerInterceptor {

//    private static final Logger logger = LoggerFactory.getLogger(WebInterceptor.class);

    /*
     * 视图渲染之后的操作
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        arg0.setAttribute("base", "/base");
    }

    /*
     * 处理请求完成后视图渲染之前的处理操作
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }

    /*
     * 进入controller层之前拦截请求
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        ResponseResult responseResult = ResponseResult.error();
        if (!AnimalConstant.open.equals(SystemUtil.getSystemParams().get(AnimalConstant.key_name_open_api_switch).getParamValue())) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            responseResult.setCode(ResultCode.FAIL).setMsg("接口未开放");
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(responseResult));
            return false;
        }

        if (AnimalConstant.open.equals(SystemUtil.getSystemParams().get(AnimalConstant.key_name_open_api_sign_switch).getParamValue())) {
            if (UtilSignature.checkSignature(request, responseResult)) {
                return true;
            } else {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.print(JSON.toJSONString(responseResult));
                return false;
            }
        } else {
            return true;
        }
    }
}
